$(function() {
    load();
    userSelect()
});

function load() {
    $('#exampleTable').bootstrapTable({
        method: 'client',
        iconSize: 'outline',
        toolbar: '#exampleToolbar',
        striped: true,
        dataType: "json",
        pagination: true,
        singleSelect: false,
        pageSize: 10,
        pageNumber: 1,
        showColumns: false,
        sidePagination: "client",
        formatNoMatches: function () {
            return '暂无学生信息';
        },
        columns: [
            {
                field: 'name',
                title: '姓名'
            },
            {
                field: 'mobile',
                title: '手机号'
            },
            {
                field: 'sex',
                title: '性别',
                formatter: function (value, row, index) {
                    return `<sapn>${value==1?'男':'女'}</sapn>`
                }
            },
            {
                title: '操作',
                field: '',
                align: 'center',
                formatter: function(value, row, index) {
                    let encodedRow = encodeURIComponent(stringifyWithoutCircular(row));
                    let e = `<a class="btn btn-primary btn-sm" href="#" mce_href="#" title="修改" onclick="add('修改学生信息','${encodedRow}','${index}')">修改</a>`;
                    let d = `<a class="btn btn-danger btn-sm" href="#" title="删除" mce_href="#" onclick="remove('${index}')">删除</a>`;
                    return  e + d;
                }
            }
        ]
    });
}

function reLoad() {
    $('#exampleTable').bootstrapTable('refresh');
}

/**
 * 查询班级
 * */
let userSelect = () => {
    $.ajax({
        type: "GET",
        url: "/sys/user/list?pageNumber=1&pageSize=10&type=1&userFrom=1",
        success: function (data) {
            let {data:{records}} = data
            if(data.code === '0') {
                $("#userId").append('<option value="">请选择</option>');
                records.map((item) => {
                    $("#userId").append(`<option value=${item.username}>${item.username}</option>`);
                })
                layui.form.render('select');
            }

        }
    });
}


/**
 * 编辑数据
 * @param {string} id
 * */
function edit(id) {
    console.log('修改')
}


/**
 * 删除数据
 * @param {string} data
 * */
function remove(data) {
    layer.confirm('确定要删除选中的记录？', {
        btn : [ '确定', '取消' ]
    }, function(layero) {
        let dataArray = $('#exampleTable').bootstrapTable('getData');
        dataArray.splice(data, 1);
        $('#exampleTable').bootstrapTable('load', dataArray);
        layer.close(layero); // 关闭弹窗时需要传入layero参数
    })
}

/**
 * 批量导入
 * */
const exports = () => {
    //文件
    layer.open({
        type: 1,
        area: ['500px', '400px'],
        title: '批量导入',
        shade: 0.6,
        shadeClose: false,
        maxmin: true,
        anim: 0,
        content:exposrtmp(),
        success: function (layero, index) {
            layui.use(['form', 'upload'],async function () {
                var form = layui.form;
                var upload = layui.upload;
                //上传
                upload.render({
                    elem: '#ID-upload-demo-drag',
                    url:'/jzweb/eclassresource/import',
                    // data: {field:$('#searchState').val()},
                    exts: 'xls',
                    done: function (res) {
                        if (res.code != "0") {
                            layer.msg(res.msg)
                            layer.confirm(`${res.data}`, {
                                btn : [ '确定' ]
                            }, function(layero) {
                                layer.close(layero); // 关闭弹窗时需要传入layero参数
                            })
                        } else {
                            layer.msg('上传成功');
                            $('#exampleTable').bootstrapTable('append', res.data);
                            // $('#exampleTable').bootstrapTable('append', formData); 新增数据
                            layer.close(index)
                            reLoad()
                        }
                    }
                });

                form.on('submit(layedit-code-yes)', function (data) {
                    const mydata = data.field

                    //关闭
                    layer.close(index);
                });
            })
        }
    });

}

const exposrtmp = () => {
    return `
        <form class="layui-form layui-form-pane" style="width: 100%;height: 100%;padding: 10px;" id="myForm">
            <div class="layui-form-item">
            <label class="layui-form-label" style="width:auto;border: 0;">导入数据需按照模板填写信息 ，<a style="color: #169bd5" href="/jzweb/eclassresource/export">点击下载模板</a></label>
            </div>
            <div class="layui-form-item" style="height: calc(100% - 150px);">
        <div class="layui-upload-drag" style=" height: 100%; display: flex; justify-content: center;  align-items: center;
        flex-direction: column;" id="ID-upload-demo-drag">
          <i class="layui-icon layui-icon-upload"></i>
          <div class="layui-icon-upload-title">点击或将拖入删除</div>
          <div class="layui-hide" id="ID-upload-demo-preview">
             上传文件
             <input type="text" name="name" placeholder="" autocomplete="off" disabled>
          </div>
        </div>
          </div>
          <div class="layui-form-item" style="display: flex;    justify-content: center;">
            <button class="layui-btn" type="button"  lay-submit lay-filter="layedit-code-yes">导入</button>
          </div>
        </form>
                `
}


/**
 * 新增 || 编辑
 * @param {string} title
 * @param {string} dataValue
 * @param {string} indexValue
 * */
const add = (title,dataValue,indexValue) => {
    let data = ''
    if (dataValue && dataValue !== "{}") { // 检查数据是否为空
        try {
            data = JSON.parse(decodeURIComponent(dataValue));
        } catch (error) {
            console.error("解析数据出错", error);
        }
    }
  let loading = layer.open({
        type: 1,
        area: ['400px', '360px'],
        title: title,
        shade: 0.6,
        shadeClose: false,
        maxmin: true,
        anim: 0,
        content: tmpData(data),
        success: function (layero, index) {
            layui.use(['form'], function(){
                var form = layui.form;
                // 初始化 select 控件

                $('#sex').val(data.sex || '');
                layui.form.render('select');

                // 监听提交事件
                form.on('submit(formDemo)', function(value){

                    if(!$('#sex').val()) return layer.msg('请选择性别')

                    if(Object.keys(data).length) {
                        $('#exampleTable').bootstrapTable('updateRow', {
                            index: indexValue,
                            row: value.field
                        });
                    }else {
                        $('#exampleTable').bootstrapTable('append',value.field);
                    }
                    layer.close(loading);
                    return false; // 阻止表单默认提交事件
                });

            });

        }
    });
}

const tmpData =(data) => {
   return `<div style="padding: 7px 20px">
               <form class="layui-form">
                    <div class="form-box">
                        <label>姓名：</label>
                        <div class="layui-input-inline">
                           <input id="name" name="name" value="${data ? data.name : ''}" type="text" required lay-verify="required" class="form-control" placeholder="请输入姓名">
                        </div>
                    </div>
                    <div class="form-box">
                        <label>手机号：</label>
                        <div class="layui-input-inline">
                            <input id="mobile" name="mobile" type="text" value="${data ? data.mobile: ''}" required lay-verify="required" class="form-control" placeholder="请输入学号">
                        </div>
                    </div>
                    <div class="form-box">
                        <label>性别：</label>
                        <div class="layui-input-inline">
                           <select id="sex" name="sex"  lay-search="" required lay-verify="required" lay-filter="select-filter">
                               <option value="1">男</option>
                               <option value="2">女</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-box" style="text-align: center">
                        <button type="button" class="layui-btn" lay-submit lay-filter="formDemo">
                            确认
                        </button>
                    </div>
                </form>
            </div>
        `
}


/**
 * 提交
 * */
const submits = () => {
    let tableValue = $('#exampleTable').bootstrapTable('getData')

    if(!$('#userId').val()){
        layer.msg('请选择创建人')
        return false
    }
    if(!$('#secretKey').val()){
        layer.msg('请输入班级名称')
        return false
    }
    if(!tableValue.length){
        layer.msg('请添加学生')
        return false
    }

    let select = $('#userId');
    let selectedIndex = select[0].selectedIndex;
    let jsonData = {
        // userId: $('#userId').val(),
        creatername:select[0].options[selectedIndex].text,
        classname:$('#secretKey').val(),
        studentVOList:tableValue,

    }
    console.log(jsonData)

    submitAdd(jsonData)
    // let index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
    // parent.layer.close(index);
}

/**
 * 生成随机id
 * */
function generateRandomId() {
    return 'id_' + Math.random().toString(36).substr(2, 9);
}

/**
 * 新增班级
 * */
const submitAdd = (jsonData) => {
    $.ajax({
        type: "POST",
        url: "/jzweb/eclassresource/inertClass",
        data: JSON.stringify(jsonData), // 将 JavaScript 对象转换为 JSON 字符串
        contentType: "application/json", // 指定发送的内容类型为 JSON
        success: function(data) {
            if (data.code === '0') {
                layer.msg('新增成功');
                parent.reLoad();
                let index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
                return
            }else {
                layer.msg(data.msg);
            }

        }
    });
}